/*
 * Copyright (C) 2009 codemobiles.com.
 * http://www.codemobiles.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * author: Chaiyasit Tayabovorn 
 * email: chaiyasit.t@gmail.com
 */

package com.codemobiles.droidslator;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.text.method.ScrollingMovementMethod;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.codemobiles.droidslator.activity.CameraPreviewActivity;
import com.codemobiles.droidslator.activity.ContactUsActivity;
import com.codemobiles.droidslator.activity.ListFlagActivity;
import com.codemobiles.droidslator.activity.SettingActivity;
import com.codemobiles.droidslator.dicts.DictSpec;
import com.codemobiles.droidslator.dicts.DictionaryFactory;
import com.codemobiles.droidslator.manager.LanguageMgr;
import com.codemobiles.droidslator.util.FontsManager;
import com.codemobiles.droidslator.util.MyUtil;
import com.google.api.translate.Language;
import com.google.api.translate.Translate;
import com.google.tts.TTS;

/**
 * 
 * @author Administrator
 */
/**
 * For SDK 1.6 Up because of TTS bundled
 */
// public class DroidslatorOldVer extends ListActivity implements OnInitListener,
// OnUtteranceCompletedListener {

public class DroidslatorOldVer extends ListActivity implements DroidslatorBase{
  private ImageView text2SpeechBtn;
  private ImageView cameraBtn;
  private ImageView messagingBtn;
  private EditText fromEditor;
  private ScrollView layEditor;
  private EditText toEditor;
  private LanguageMgr langMgr;
  private FrameLayout fraFlag;
  private ImageView imgBanner;
  private AlertDialog dlgListViewIcon;
  private AlertDialog dlgAlert;
  private SimpleImage imgFocus;
  private SelectionView selectView;
  private TextView txvTitle;
  private static ArrayAdapter<String> adapter = null;
  private static List<String> likeWordsList = new ArrayList<String>();
  private String strError;
  private final int SEARCHED_NOT_BEGUN = 0x00;
  private final int SEARCHED_NOT_FOUND = 0x01;
  private final int SEARCHED_AND_FOUND = 0x02;
  private int SEARCH_STATE = SEARCHED_NOT_BEGUN;
  private Builder setupAlert;
  private DisplayMetrics displayMetrics;
  private int startTouchX = 0;
  private int startTouchY = 0;
  ViewFlipper flipper;
  private AppPreferences appPref;
  private static final int DIALOG_ALERT = 2;
  private static final int DIALOG_LIST_CONFIG = 3;
  private String selectedFlagType = "N/A";
  private static final int LIST_FLAG_ACTIVITY_ID = 0x001;
  private static final int LIST_CAMERA_ACTIVITY_ID = 0x002;
  private static final int MY_DATA_CHECK_CODE = 0x003;
  private static Context m_context;
  private TTS myTts;

  private String lastWords;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.main);
    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
    appPref = AppPreferences.getInstance(this);
    m_context = this;
    FontsManager.init(this);

    if (appPref.getBooleanValueOf(AppPreferences.PLUGIN_LEXITRON) == false) {
      setupOfflineDictAlerts();
      setupAlert.show();
    }

    // get screen width and height
    displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    langMgr = new LanguageMgr(this);

    text2SpeechBtn = (ImageView) findViewById(R.id.imgTranslate);
    cameraBtn = (ImageView) findViewById(R.id.imgEraser);
    messagingBtn = (ImageView) findViewById(R.id.imgMessaging);
    fromEditor = (EditText) findViewById(R.id.fromEditor);
    layEditor = (ScrollView) findViewById(R.id.layEditor);
    toEditor = (EditText) findViewById(R.id.toEditor);
    fraFlag = (FrameLayout) findViewById(R.id.fraFlag);
    txvTitle = (TextView) findViewById(R.id.txvTitle);
    imgBanner = (ImageView) findViewById(R.id.imgBanner);

    // set bulit-in font
    toEditor = FontsManager.getSupportedFontEditText(toEditor);
    
    setInitFromEditText();
    setInitToEditText();
    setInitText2SpeechButton();
    setInitCameraButton();
    setInitMessagingButton();
    getListView().setTextFilterEnabled(true);
    flipper = (ViewFlipper) findViewById(R.id.details);

    likeWordsList.clear();
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, likeWordsList) {

      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
        TextView txt = new TextView(this.getContext());

        // set bulit-in font (thai by droidsans.com)
        txt = FontsManager.getSupportedFontTextView(txt);        
        txt.setTextColor(Color.BLACK);
        txt.setTextSize(15);
        txt.setText(this.getItem(position));
        return txt;

      }

    };

    setListAdapter(adapter);

    // Draw flag and add to FrameLayout
    selectView = new SelectionView(this, displayMetrics);
    fraFlag.addView(selectView);

    // Set translation title
    setTranslateTitle();
    
   
   // initial TTS
    if (TTS.isInstalled(m_context) == true) {
      if (myTts == null) {
        myTts = new TTS(m_context, ttsInitListener, true);
      }
    }
    

  }

  public static Context getM_context() {
    return m_context;
  }

  public static void setM_context(Context mContext) {
    m_context = mContext;
  }

  private final int MENU_ABOUTUS = 0x001;
  private final int MENU_SETUP = 0x002;
  private final int MENU_DONATE = 0x003;
  private final int MENU_UPGRADE_APP = 0x004;

  @Override
  protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    swapBannerImage(VISIBLE_BANNER_IMG);
  }

  @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);
    String selectedWords = likeWordsList.get(position);
    selectedWords = selectedWords.substring(0, selectedWords.indexOf(":")).trim();
    translateIt(selectedWords);
    fromEditor.setText(selectedWords);
    hideKeyboard(fromEditor.getWindowToken());
    flipper.setDisplayedChild(2);
    swapBannerImage(VISIBLE_BANNER_IMG);

  }

  /**
   * Called to setup option menu
   */
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {

    menu.add(1, MENU_SETUP, 1, "Setup").setIcon(R.drawable.setup_icon);
    menu.add(1, MENU_ABOUTUS, 2, "AboutUS").setIcon(R.drawable.we_icon);
    menu.add(1, MENU_DONATE, 3, "Donate").setIcon(R.drawable.donate_icon);
    menu.add(1, MENU_UPGRADE_APP, 4, "Upgrade").setIcon(R.drawable.upgrade);

    return true;
  }

  /**
   * Called when item in option menu is selected
   */
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case MENU_ABOUTUS:
      Intent iContactUs = new Intent(DroidslatorOldVer.this, ContactUsActivity.class);
      startActivity(iContactUs);
      return true;
    case MENU_SETUP:
      Intent iSetting = new Intent(DroidslatorOldVer.this, SettingActivity.class);
      startActivity(iSetting);
      return true;
    case MENU_DONATE:
      MyUtil.callWebBrowser("http://www.codemobiles.com/donate.html", DroidslatorOldVer.this);
      return true;
    case MENU_UPGRADE_APP:
      MyUtil.callWebBrowser("http://www.codemobiles.com/droidslator/droids_beta.apk", DroidslatorOldVer.this);
    }
    return false;
  }

  private void setInitMessagingButton() {
    messagingBtn.setOnTouchListener(new OnTouchListener() {

      @Override
      public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        int eventaction = event.getAction();

        switch (eventaction) {

        case MotionEvent.ACTION_DOWN:
          messagingBtn.setImageResource(R.drawable.button_messaging_touch);
          break;

        case MotionEvent.ACTION_MOVE:
          break;

        case MotionEvent.ACTION_UP:
          messagingBtn.setImageResource(R.drawable.button_messaging);
          break;
        }

        return false;
      }
    });
    messagingBtn.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        hideKeyboard(fromEditor.getWindowToken());
        Intent sendIntent = new Intent(Intent.ACTION_VIEW);
        String tmp = toEditor.getText().toString();
        tmp = tmp.replace("From: (Offline Dictionary)\n\n", "");
        tmp = tmp.replace("From: (Online Dictionary)\n\n", "");
        sendIntent.putExtra("sms_body", tmp);
        sendIntent.setType("vnd.android-dir/mms-sms");
        startActivity(sendIntent);

      }
    });

    fromEditor.setOnTouchListener(new OnTouchListener() {

      @Override
      public boolean onTouch(View v, MotionEvent event) {
        int eventaction = event.getAction();
        int X = (int) event.getX();
        int Y = (int) event.getY();

        switch (eventaction) {

        case MotionEvent.ACTION_DOWN:
          startTouchX = X;
          startTouchY = Y;
          break;

        case MotionEvent.ACTION_MOVE:
          break;

        case MotionEvent.ACTION_UP:
          int startX = fromEditor.getLeft();
          int endX = fromEditor.getRight();
          int widthDetectAction = displayMetrics.widthPixels / 6; // 16.67%
          if (startTouchX < startX && startTouchX > endX) {
            break;
          }

          startX = layEditor.getLeft();
          endX = layEditor.getRight();

          // if touch position released out of this object not take
          // action
          if (X - startTouchX > widthDetectAction) {
            clearInput();
          }

          int startY = fromEditor.getTop();
          int endY = fromEditor.getBottom();
          int HeightDetectAction = displayMetrics.heightPixels / 6; // 16.67%
          if (startTouchY < startY && startTouchY > endY) {
            break;
          }

          startY = layEditor.getLeft();
          endY = layEditor.getRight();

          // if touch position released out of this object not take
          // action
          if (Y - startTouchY > HeightDetectAction) {
            hideKeyboard(fromEditor.getWindowToken());
            translateIt(fromEditor.getText().toString());
          }
        }

        return false;
      }
    });
  }

  private void setInitText2SpeechButton() {
    text2SpeechBtn.setOnTouchListener(new OnTouchListener() {

      @Override
      public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        int eventaction = event.getAction();

        switch (eventaction) {

        case MotionEvent.ACTION_DOWN:
          text2SpeechBtn.setImageResource(R.drawable.button_speaker_touch);
          break;

        case MotionEvent.ACTION_MOVE:
          break;

        case MotionEvent.ACTION_UP:
          text2SpeechBtn.setImageResource(R.drawable.button_speaker);
          break;
        }

        return false;
      }
    });
    text2SpeechBtn.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {

        /**
         * 1.6+ only
         */
        
          //Intent checkIntent = new Intent();
         // checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
          //startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
         

        //initial TTS;
        
        if (TTS.isInstalled(m_context) == true) {
          if (myTts == null) {
            myTts = new TTS(m_context, ttsInitListener, true);
          }        
          myTts.speak(fromEditor.getText().toString(), 0, null);
        } else {
          showSetUpTTSDialogBox();
        }
        

      }
    });
  }

  /*
  private TTS.InitListener ttsInitListener = new TTS.InitListener() {
    public void onInit(int version) {
    }
  };
  */

  private void showSetUpTTSDialogBox() {
    setupAlert = new AlertDialog.Builder(this).setTitle("Install Text2Speech Plug-in").setMessage(
        "Install Now?, Recommended!!! (After download completes, Please install it)").setPositiveButton("Yes", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {
        callWebBrowser("http://www.codemobiles.com/droidslator/tts_2.0_market.apk", m_context);

      }
    }).setNegativeButton("No", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {

      }
    });
    setupAlert.show();
  }

  public static void callWebBrowser(final String uriStr, Context context) {
    Intent i = new Intent("android.intent.action.VIEW", Uri.parse(uriStr));
    context.startActivity(i);
  }

  private void setInitCameraButton() {
    cameraBtn.setOnTouchListener(new OnTouchListener() {

      @Override
      public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        int eventaction = event.getAction();

        switch (eventaction) {

        case MotionEvent.ACTION_DOWN:
          cameraBtn.setImageResource(R.drawable.button_camera_touch);
          break;

        case MotionEvent.ACTION_MOVE:
          break;

        case MotionEvent.ACTION_UP:
          cameraBtn.setImageResource(R.drawable.button_camera);
          break;
        }

        return false;
      }
    });
    cameraBtn.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        hideKeyboard(fromEditor.getWindowToken());

        /*
         * final String pluginName = getString(R.string.plugin_ocr_en);
         * 
         * if (appPref.getBooleanValueOf(pluginName)){
         * 
         * }
         */

        if (appPref.getBooleanValueOf(AppPreferences.PLUGIN_OCR_EN) == false) {
          setupEnglishOCRAlerts();
          setupAlert.show();
        }else{
          Intent iCameraPreview = new Intent(DroidslatorOldVer.this, CameraPreviewActivity.class);
          startActivityForResult(iCameraPreview, LIST_CAMERA_ACTIVITY_ID);
        }
        
      }
    });
  }

  private void clearInput() {
    fromEditor.setText("");
    toEditor.setText("");
  }

  private void setInitFromEditText() {

    fromEditor.addTextChangedListener(new TextWatcher() {

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub

      }

      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // TODO Auto-generated method stub

      }

      @Override
      public void afterTextChanged(Editable s) {
        final int inputLen = fromEditor.getText().toString().trim().length();

        if (inputLen < 2) {
          if (inputLen < 1) {
            swapBannerImage(VISIBLE_BANNER_IMG);
          } else {
            swapBannerImage(INVISIBLE_BANNER_IMG);
          }
          likeWordsList.clear();
          adapter.notifyDataSetChanged();
          SEARCH_STATE = SEARCHED_NOT_BEGUN;
        } else {

          swapBannerImage(INVISIBLE_BANNER_IMG);

          boolean willDoPreSearch_factor1 = ((SEARCH_STATE == SEARCHED_NOT_BEGUN) || (SEARCH_STATE == SEARCHED_AND_FOUND));
          boolean willDoPreSearch_factor2 = ((SEARCH_STATE == SEARCHED_NOT_FOUND) && (fromEditor.getText().toString().length() < lastWords.length()));

          // when during searching or beginning of search
          if (willDoPreSearch_factor1 || willDoPreSearch_factor2) {
            if (preLookUp() == true) {
              SEARCH_STATE = SEARCHED_AND_FOUND;
              flipper.setDisplayedChild(1);
            } else {
              SEARCH_STATE = SEARCHED_NOT_FOUND;
            }
            adapter.notifyDataSetChanged();
          }
        }

        lastWords = fromEditor.getText().toString();

      }

    });

    fromEditor.setOnKeyListener(new View.OnKeyListener() {

      @Override
      public boolean onKey(View v, int keyCode, KeyEvent event) {

        if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
          swapBannerImage(VISIBLE_BANNER_IMG);
        }

        if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
          // Perform action on key press
          translateIt(fromEditor.getText().toString().trim());
          hideKeyboard(fromEditor.getWindowToken());
          flipper.setDisplayedChild(2);
          return true;
        }
        return false;
      }
    });
    fromEditor.setOnFocusChangeListener(new OnFocusChangeListener() {

      @Override
      public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
          hideKeyboard(fromEditor.getWindowToken());
        }
      }
    });
  }

  private void setInitToEditText() {
    toEditor.setMovementMethod(new ScrollingMovementMethod());
  }

  private void hideKeyboard(IBinder curWindowToken) {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(curWindowToken, 0);
  }

  
    // Set initiate TTS 
  private TTS.InitListener ttsInitListener = new TTS.InitListener() { public void onInit(int version) { } };
   

  private boolean preLookUp() {
    String fromLangCode = selectView.getFromFlagCode();
    String toLangCode = selectView.getToFlagCode();
    final String inputWord = fromEditor.getText().toString().trim();
    String toLangName = langMgr.getLangNameByCode(toLangCode);
    String fromLangName = langMgr.getLangNameByCode(fromLangCode);
    DictSpec dict = DictionaryFactory.getDictionary(fromLangName);
    // return false if can't find proper dict engine
    if (dict == null) return false;
    // relist similar words
    likeWordsList.clear();
    dict.loadSimilar(inputWord, toLangName, likeWordsList);
    return (likeWordsList.size() > 0);
  }

  private void translateIt(String inputWord) {
    String fromLangCode = selectView.getFromFlagCode();
    String toLangCode = selectView.getToFlagCode();    
    appPref.setValueOf(AppPreferences.FROM_LANG_CODE, fromLangCode);
    appPref.setValueOf(AppPreferences.TO_LANG_CODE, toLangCode);
    
    String fromLangName = langMgr.getLangNameByCode(fromLangCode);
    String toLangName = langMgr.getLangNameByCode(toLangCode);
    StringBuffer res = new StringBuffer();

    // verify input data
    if (inputWord == null || inputWord.length() == 0) {
      return;
    }

    // formalize
    inputWord = inputWord.replace("'", "''");

    try {
      DictSpec dict = DictionaryFactory.getDictionary(fromLangName);
      if (dict != null) {
        final String GOOGLE_TRANSLATOR_URL = "http://code.google.com/p/google-api-translate-java/";
        // Set the HTTP referrer to your web site address.
        Translate.setHttpReferrer(GOOGLE_TRANSLATOR_URL);

        res.append(dict.translate(inputWord, toLangName));
        if (res.toString().equals("") != true) {
          res.insert(0, "From: (Offline Dictionary)\n\n");
        }
        toEditor.setText(res);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }

    if (res.toString().equals("")) {

      try {
        ConnectivityManager internetConn = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = internetConn.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected() == true) {
          res.append(Translate.translate(inputWord, Language.valueOf(fromLangName), Language.valueOf(toLangName)));
          if (res.toString().equals("") != true) {
            final String GOOGLE_TRANSLATOR_URL = "http://code.google.com/p/google-api-translate-java/";
            // Set the HTTP referrer to your web site address.
            Translate.setHttpReferrer(GOOGLE_TRANSLATOR_URL);
            res.insert(0, "From: (Online Dictionary)\n\n");
          }
        }
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    if (res.toString().equalsIgnoreCase("")) {
      res.append("!!! Sorry, not found your words needed to translate in offline database and the device is now also not connected to the Internet");
      toEditor.setText(res.toString());
      return;
    }
    toEditor.setText(res.toString());

    String mTo = toEditor.getText().toString();
    final int hOfferset = mTo.toString().indexOf("\n");
    String mHead = mTo.substring(0, hOfferset);
    String mBody = mTo.substring(hOfferset, mTo.length());

    mBody = mBody.replace("\n", "<br>");
    mHead = mHead.replace(mHead, "<u><font color=#001d99>" + mHead + "</font></u>");
    toEditor.setText(Html.fromHtml(mHead + mBody));

    flipper.setDisplayedChild(2);
  }

  public void swapText() {
    String tmp = fromEditor.getText().toString();
    fromEditor.setText(toEditor.getText());
    toEditor.setText(tmp);
  }

  public void showListConfig() {
    if (dlgListViewIcon == null) {
      showDialog(DIALOG_LIST_CONFIG);
    } else {
      dlgListViewIcon.show();
    }
  }

  public void showList(SimpleImage img, String lastRegStr) {
    imgFocus = img;
    Intent intent = new Intent(this.getApplicationContext(), ListFlagActivity.class);
    intent.putExtra("lastReg", lastRegStr);
    startActivityForResult(intent, LIST_FLAG_ACTIVITY_ID);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
    case (LIST_FLAG_ACTIVITY_ID): {
      if (data == null)
        return;
      String flagCode = data.getExtras().get("FLAG_CODE").toString();      
      if (flagCode != null) {
        if (selectView.setBitmapFile(flagCode, imgFocus)) {
          setTranslateTitle();
        } else {
          showAlert(getString(R.string.alert_flag_duplicate));
        }
      }
      break;
    }
    case (LIST_CAMERA_ACTIVITY_ID): {
      if (data == null)
        return;
      fromEditor.setText(data.getExtras().get("Result").toString());
      break;
    }
    /*  
    case (MY_DATA_CHECK_CODE): { if (resultCode ==
        TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) { 
        mTts = new TextToSpeech(this, (OnInitListener) this);
        
        } else { // missing data, install it 
          Intent installIntent = new Intent();
        installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
        startActivity(installIntent); }
        
        }
        */
       
    }

  }

  public void showAlert(String text) {
    if (dlgAlert == null) {
      showDialog(DIALOG_ALERT);
    } else {
      dlgAlert.setMessage(text);
      dlgAlert.show();
    }
  }

  @Override
  protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_ALERT:
      dlgAlert = new AlertDialog.Builder(DroidslatorOldVer.this).setMessage(strError).create();
      return dlgAlert;

    }

    return null;
  }

  private final int VISIBLE_BANNER_IMG = 0x01;
  private final int INVISIBLE_BANNER_IMG = 0x02;
  private int mCurrentBannerImage = VISIBLE_BANNER_IMG;

  private void swapBannerImage(int imageID) {

    // when need to show banner
    if (imageID == VISIBLE_BANNER_IMG && mCurrentBannerImage == INVISIBLE_BANNER_IMG) {
      mCurrentBannerImage = VISIBLE_BANNER_IMG;
      imgBanner.setImageResource(R.drawable.banner);
      imgBanner.invalidate();
    } // when need to hide banner
    else if (imageID == INVISIBLE_BANNER_IMG && mCurrentBannerImage == VISIBLE_BANNER_IMG) {
      mCurrentBannerImage = INVISIBLE_BANNER_IMG;
      imgBanner.setImageResource(R.drawable.back_translate_from_middle);
      imgBanner.invalidate();
    }
  }

  public void setTranslateTitle() {
    String FromFlagName = langMgr.convertNameToShort(langMgr.getLangNameByCode(selectView.getFromFlagCode()));
    String ToFlagName = langMgr.convertNameToShort(langMgr.getLangNameByCode(selectView.getToFlagCode()));
    txvTitle.setText(FromFlagName + " >> " + ToFlagName + " ");
  }

  // 1.6+ only
  // private TextToSpeech mTts;

  /**
   * only for 1.6+
   * 
   * @param utteranceId
   */
  // @Override 
  // public void onInit(int arg0) { // TODO Auto-generated method stub
  //  mTts.setLanguage(Locale.US); mTts.speak(fromEditor.getText().toString(),
  //  TextToSpeech.QUEUE_FLUSH, null);
    
   // }
  

  /**
   * only for 1.6+
   * 
   * @param utteranceId
   */

  /*
   * @Override public void onUtteranceCompleted(String utteranceId) { if
   * (utteranceId == "end of wakeup message ID") {
   * 
   * }
   * 
   * }
   */

  @Override
  protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();

    // 1.6++
    
    // if (mTts != null) { mTts.shutdown(); }
    
  }

  private void setupOfflineDictAlerts() {
    setupAlert = null;
    setupAlert = new AlertDialog.Builder(this).setTitle("Setup Core-Library ")

    .setMessage("Setup Now, Recommended!!!?").setPositiveButton("Yes", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {
        Intent iSetting = new Intent(DroidslatorOldVer.this, SettingActivity.class);
        Bundle b = new Bundle();
        b.putBoolean("PLUGIN_001", true);
        iSetting.putExtras(b);
        startActivity(iSetting);
      }
    }).setNegativeButton("No", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {

      }
    });
  }
  
  private void setupEnglishOCRAlerts() {
    setupAlert = null;
    setupAlert = new AlertDialog.Builder(this).setTitle("Install OCR Plug-in ")

    .setMessage("Setup Now? Required Internet Access!").setPositiveButton("Yes", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {
        Intent iSetting = new Intent(DroidslatorOldVer.this, SettingActivity.class);
        Bundle b = new Bundle();
        b.putBoolean("PLUGIN_002", true);
        iSetting.putExtras(b);
        startActivity(iSetting);
      }
    }).setNegativeButton("No", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {

      }
    });
  }

  public void onInit(int arg0, int arg1) {
    // TODO Auto-generated method stub
    
  }

}